/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.scmt.hmzd.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.scmt.core.common.exception.ScmtException;
import com.scmt.core.common.utils.ResultUtil;
import com.scmt.core.common.vo.Result;
import com.scmt.hmzd.utils.HttpClientUtil;
import com.scmt.hmzd.utils.Md5Util;
import com.scmt.hmzd.utils.WxUtils;
import com.scmt.hmzd.utils.XmlUtil;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.poi.hpsf.Decimal;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 通过微信配置获取微信的支付信息，登陆信息等
 *
 * @author LGH
 */
@Component
@AllArgsConstructor
@Slf4j
public class WxConfig {
    private final RedissonClient redissonClient;

    private final Snowflake snowflake;

    public WxMpService getWxMpService() {
        WxMp wxMp = new WxMp();
        wxMp.setAppId(WeixinPayConfig.appid);
        wxMp.setSecret(WeixinPayConfig.secret);
        wxMp.setToken("");
        wxMp.setAesKey("");
        WxMpInRedisConfigStorage wxMaInRedisConfig = new WxMpInRedisConfigStorage(wxMp);
        WxMpServiceClusterImpl service = new WxMpServiceClusterImpl();
        service.setWxMpConfigStorage(wxMaInRedisConfig);
        service.setRedissonClient(redissonClient);
        return service;
    }

    /**
     * 微信支付签名算法sign
     */
    public static String getSign(Map<String, Object> map) {
        StringBuffer sb = new StringBuffer();
        String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
        Arrays.sort(keyArr);//对array排序
        for (int i = 0, size = keyArr.length; i < size; ++i) {
            if ("sign".equals(keyArr[i])) {
                continue;
            }
            sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
        }
        sb.append("key=" + WeixinPayConfig.key);
        String sign = Md5Util.string2MD5(sb.toString());
        return sign;
    }


    public String getWxgAccessToken() {
        // 服务号的appid以及秘钥
        String appid = WeixinPayConfig.appid;
        String Wxgsecret = WeixinPayConfig.secret;
        String requestUrl = StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}", appid, Wxgsecret);
        String returnMsg = HttpUtil.get(requestUrl);
        cn.hutool.json.JSONObject responseJsonObject = JSONUtil.parseObj(returnMsg);
        log.info("获取微信token：{}", responseJsonObject);
        if (ObjectUtil.isNull(responseJsonObject)) {
            throw new ScmtException("获取token失败！");
        }
        String accessToken = responseJsonObject.getStr("access_token");
        return accessToken;
    }


    public Boolean sendWxgMessage(String orderId, String openId, String projectName, String orderNumber, String serviceTime) {
        String wxgAccessToken = getWxgAccessToken();

        // 组装消息内容
        String templateId = "P14k2RQTjJ1xTxo_f32r5jbKyQVsfmKePEyPM_l_ZwA"; // 模板id
        String url = "https://jcepay.lzjczl.com/wxHtml/pages/js/index?orderId=" + orderId;       // 跳转路径(小程序之外)
        String first = "你有一个新的订单";  // 副标题
        String remark = "更多详情信息请点击查看";  // 备注
//        projectName = "精油开背";  // 服务名称
//        orderNumber = "1636640840271138816";  // 订单编号
//        serviceTime = "2022-03-19 17:30";  // 服务时间
        String messageStr = "{\n" +
                "           \"touser\":" + "\"" + openId + "\"" + ",\n" +
                "           \"template_id\":" + "\"" + templateId + "\"" + ",\n" +
                "           \"url\":" + "\"" + url + "\"" + ",  \n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":" + "\"" + first + "\"" + ",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"thing2\":{\n" +
                "                       \"value\":" + "\"" + projectName + "\"" + ",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"number1\": {\n" +
                "                       \"value\":" + "\"" + orderNumber + "\"" + ",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"time6\": {\n" +
                "                       \"value\":" + "\"" + serviceTime + "\"" + ",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":" + " \"" + remark + "\"" + ",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";

        // 发送消息
        String returnMsg = HttpUtil.post(StrUtil.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}", wxgAccessToken), messageStr);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(returnMsg);
        log.info("发送微信模板消息：{}", jsonObject);
        String errmsg = jsonObject.getStr("errmsg");
        if (!StrUtil.equals("ok", errmsg)) {
            return false;
        }
        return true;
    }


    /**
     * 发送红包
     *
     * @return
     */
    public boolean sendRedpack(String openId, Double money) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        String redPackOrderNumber = String.valueOf(snowflake.nextId());

        WxUtils wxUtils = new WxUtils();
        map.put("nonce_str", UUID.randomUUID().toString().replace("-", "")); //随机字符串，不长于32位
        map.put("mch_billno", redPackOrderNumber);//商户订单号
        // 商户号
        map.put("mch_id", WeixinPayConfig.mch_id);
        // 公众账号ID
        map.put("wxappid", WeixinPayConfig.appid);
        map.put("send_name", "思缘到家");//红包发送者名称
        map.put("re_openid", openId);//用户openid
        map.put("total_amount", 1);//	付款金额，单位分
        map.put("total_num", 1);//	红包发放总人数
        map.put("wishing", "收到项目服务费");//	红包祝福语
        map.put("client_ip", "192.168.5.49");//	ip
        map.put("act_name", "项目服务费");//活动名称
        map.put("remark", "服务越多得越多，快去接单吧！");//备注
        map.put("sign", WxConfig.getSign(map)); //签名

        String xml = XmlUtil.genXml(map);
        HttpResponse httpResponse = HttpClientUtil.sendXMLDataByPost(WeixinPayConfig.send_redpack_url, xml);
        HttpEntity entity = httpResponse.getEntity();
        InputStream content = entity.getContent();
        Map<String, Object> elementValueToMap = wxUtils.getElementValueToMap(content);
        String result_code = elementValueToMap.get("result_code").toString();
        if (StringUtil.isNotEmpty(result_code) && "SUCCESS".equals(result_code.toUpperCase())) {
            return true;
        } else {
            //调用查询接口  确保红包是否发送成功
            HttpResponse redResponse = queryRedPackInfo(redPackOrderNumber);
            entity = redResponse.getEntity();
            content = entity.getContent();
            elementValueToMap = wxUtils.getElementValueToMap(content);
            result_code = elementValueToMap.get("result_code").toString();
            if (StringUtil.isNotEmpty(result_code) && "SUCCESS".equals(result_code.toUpperCase())) {
                String status = elementValueToMap.get("status").toString();
//                SENDING:发放中
//                SENT:已发放待领取
//                FAILED：发放失败
//                RECEIVED:已领取
//                RFUND_ING:退款中
//                REFUND:已退款
                if (!StringUtil.equals(status, "FAILED") && !StringUtil.equals(status, "SENDING")) {
                    return true;
                }
            }
        }
        return false;
    }


    public HttpResponse queryRedPackInfo(String redPackOrderNumber) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nonce_str", UUID.randomUUID().toString().replace("-", "")); //随机字符串，不长于32位
        map.put("mch_billno", redPackOrderNumber);//商户订单号
        // 商户号
        map.put("mch_id", WeixinPayConfig.mch_id);
        map.put("appid", WeixinPayConfig.appid);
        map.put("bill_type", "MCHT");
        map.put("sign", WxConfig.getSign(map)); //签名
        String xml = XmlUtil.genXml(map);
        HttpResponse httpResponse = HttpClientUtil.sendXMLDataByPost(WeixinPayConfig.query_redpack_url, xml);
        return httpResponse;
    }


}
